package com.ccz.demo.design.combination;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@Data
@NoArgsConstructor
public class Composite extends Component{

    private String name;

    private List<Component> child = null;

    public Composite(String name) {
        this.name = name;
    }

    @Override
    public void operation(String preStr) {
        System.out.println("输出自己:" + name + "-" + preStr);
        // 如果有子节点输出子节点
        if (child != null) {
            preStr += " ";
            for (Component component : child) {
                component.operation(preStr);
            }
        }
    }

    @Override
    public void add(Component c) {
        if (child == null) {
            child = new ArrayList<>();
        }
        child.add(c);
    }

    @Override
    public void remove(Component c) {
        if (child != null) {
            child.remove(c);
        }
    }

    @Override
    public Component getChild(int i) {
        if (i >= 0 && child != null && i < child.size()) {
            return child.get(i);
        }
        return null;
    }
}
